<template>
  <div class="login-container">
    <div class="login-background">
      <div class="background-pattern"></div>
      <div class="floating-elements">
        <div class="floating-element" v-for="n in 6" :key="n"></div>
      </div>
    </div>
    
    <div class="login-card">
      <div class="login-header">
        <div class="app-icon">
          <div class="icon-wrapper">
            <el-icon :size="56"><Lock /></el-icon>
          </div>
        </div>
        <h1 class="app-title">密码管理器</h1>
        <p class="app-subtitle" v-if="isFirstTime">
          欢迎使用！请设置您的主密码
        </p>
        <p class="app-subtitle" v-else>
          请输入主密码解锁您的账号
        </p>
      </div>

      <el-form 
        ref="loginForm" 
        :model="form" 
        :rules="rules" 
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入主密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
            :loading="loading"
            clearable
          />
        </el-form-item>

        <el-form-item prop="confirmPassword" v-if="isFirstTime">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请确认主密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
            clearable
          />
        </el-form-item>

        <div class="password-strength" v-if="isFirstTime && form.password">
          <div class="strength-label">密码强度：</div>
          <div class="strength-bar">
            <div 
              class="strength-fill" 
              :class="strengthClass"
              :style="{ width: strengthWidth }"
            ></div>
          </div>
          <div class="strength-text" :class="strengthClass">
            {{ strengthText }}
          </div>
        </div>

        <el-alert
          v-if="errorMessage"
          :title="errorMessage"
          type="error"
          :closable="false"
          class="error-alert"
        />

        <div class="login-actions">
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            class="login-button"
          >
            {{ isFirstTime ? '设置主密码' : '解锁' }}
          </el-button>
        </div>
      </el-form>

      <div class="security-tips">
        <div class="tips-title">
          <el-icon><InfoFilled /></el-icon>
          <span>安全提示</span>
        </div>
        <div class="tips-content">
          <div class="tip-item">
            <div class="tip-icon">
              <el-icon><Lock /></el-icon>
            </div>
            <span>主密码用于加密您的所有数据</span>
          </div>
          <div class="tip-item">
            <div class="tip-icon">
              <el-icon><WarnTriangleFilled /></el-icon>
            </div>
            <span>请务必记住主密码，忘记后无法恢复</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { ElMessage } from 'element-plus'
import { Lock, InfoFilled, WarnTriangleFilled } from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

const loginForm = ref()
const loading = ref(false)
const errorMessage = ref('')
const isFirstTime = ref(false)

const form = reactive({
  password: '',
  confirmPassword: ''
})

// 验证规则
const rules = reactive({
  password: [
    { required: true, message: '请输入主密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少8位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认主密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 密码强度计算
const passwordStrength = computed(() => {
  const password = form.password
  if (!password) return 0

  let score = 0
  
  // 长度
  if (password.length >= 8) score += 1
  if (password.length >= 12) score += 1
  
  // 字符类型
  if (/[a-z]/.test(password)) score += 1
  if (/[A-Z]/.test(password)) score += 1
  if (/[0-9]/.test(password)) score += 1
  if (/[^a-zA-Z0-9]/.test(password)) score += 1
  
  return Math.min(score, 5)
})

const strengthWidth = computed(() => `${(passwordStrength.value / 5) * 100}%`)

const strengthClass = computed(() => {
  const strength = passwordStrength.value
  if (strength <= 1) return 'weak'
  if (strength <= 2) return 'fair'
  if (strength <= 3) return 'good'
  if (strength <= 4) return 'strong'
  return 'very-strong'
})

const strengthText = computed(() => {
  const strength = passwordStrength.value
  if (strength <= 1) return '很弱'
  if (strength <= 2) return '较弱'
  if (strength <= 3) return '一般'
  if (strength <= 4) return '较强'
  return '很强'
})

// 检查是否首次使用
const checkFirstTime = async () => {
  try {
    const hasDataFile = await window.electronAPI.checkDataFile()
    isFirstTime.value = !hasDataFile
  } catch (error) {
    console.error('检查首次使用状态失败:', error)
    isFirstTime.value = true
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginForm.value) return
  
  try {
    await loginForm.value.validate()
    
    if (isFirstTime.value && passwordStrength.value < 2) {
      ElMessage.warning('密码强度太弱，请设置一个更强的密码')
      return
    }
    
    loading.value = true
    errorMessage.value = ''
    
    const result = await authStore.login(form.password)
    
    if (result.success) {
      // 显示成功消息
      if (result.isFirstTime) {
        ElMessage.success('主密码设置成功！')
      } else {
        ElMessage.success('登录成功！')
      }
      
      // 短暂延迟后跳转，让用户看到成功消息
      setTimeout(() => {
        router.push('/main')
      }, 800)
    } else {
      errorMessage.value = result.message
    }
  } catch (error) {
    if (error.fields) {
      // 表单验证错误
      return
    }
    console.error('登录失败:', error)
    errorMessage.value = '登录失败，请重试'
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  checkFirstTime()
})
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.background-pattern {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 25% 25%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 75% 75%, rgba(255, 255, 255, 0.05) 0%, transparent 50%);
  animation: patternMove 20s ease-in-out infinite alternate;
}

@keyframes patternMove {
  0% { transform: translateX(-20px) translateY(-20px); }
  100% { transform: translateX(20px) translateY(20px); }
}

.floating-elements {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.floating-element {
  position: absolute;
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 50%;
  animation: float 6s ease-in-out infinite;
}

.floating-element:nth-child(1) {
  top: 10%;
  left: 10%;
  animation-delay: 0s;
  animation-duration: 6s;
}

.floating-element:nth-child(2) {
  top: 20%;
  right: 10%;
  animation-delay: 1s;
  animation-duration: 8s;
}

.floating-element:nth-child(3) {
  top: 60%;
  left: 5%;
  animation-delay: 2s;
  animation-duration: 7s;
}

.floating-element:nth-child(4) {
  bottom: 20%;
  right: 20%;
  animation-delay: 3s;
  animation-duration: 9s;
}

.floating-element:nth-child(5) {
  bottom: 10%;
  left: 20%;
  animation-delay: 4s;
  animation-duration: 5s;
}

.floating-element:nth-child(6) {
  top: 40%;
  right: 30%;
  animation-delay: 5s;
  animation-duration: 10s;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(180deg); }
}

.login-card {
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  padding: 48px 40px;
  width: 100%;
  max-width: 440px;
  box-shadow: 
    0 32px 64px rgba(0, 0, 0, 0.15),
    0 0 0 1px rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  position: relative;
  z-index: 10;
  animation: cardSlideIn 0.8s ease-out;
}

@keyframes cardSlideIn {
  0% {
    opacity: 0;
    transform: translateY(30px) scale(0.95);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 36px;
}

.app-icon {
  margin-bottom: 20px;
}

.icon-wrapper {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
  animation: iconPulse 2s ease-in-out infinite;
}

@keyframes iconPulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.05); }
}

.icon-wrapper .el-icon {
  color: white;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.app-title {
  font-size: 32px;
  font-weight: 700;
  color: #2d3748;
  margin: 0 0 12px 0;
  background: linear-gradient(135deg, #2d3748 0%, #4a5568 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.app-subtitle {
  font-size: 16px;
  color: #718096;
  margin: 0;
  line-height: 1.6;
  font-weight: 500;
}

.login-form {
  margin-bottom: 28px;
}

.login-form .el-form-item {
  margin-bottom: 24px;
}

.login-form :deep(.el-input) {
  height: 52px;
}

.login-form :deep(.el-input__wrapper) {
  background: rgba(247, 250, 252, 0.9);
  border: 2px solid rgba(226, 232, 240, 0.8);
  border-radius: 12px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper:hover) {
  border-color: rgba(102, 126, 234, 0.4);
}

.login-form :deep(.el-input.is-focus .el-input__wrapper) {
  border-color: #667eea;
  box-shadow: 
    inset 0 1px 3px rgba(0, 0, 0, 0.05),
    0 0 0 4px rgba(102, 126, 234, 0.1);
}

.login-form :deep(.el-input__inner) {
  font-size: 16px;
  font-weight: 500;
  color: #2d3748;
}

.password-strength {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 12px;
  font-size: 14px;
  padding: 8px 0;
}

.strength-label {
  color: #4a5568;
  font-weight: 600;
  min-width: 60px;
}

.strength-bar {
  flex: 1;
  height: 6px;
  background: #e2e8f0;
  border-radius: 3px;
  overflow: hidden;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}

.strength-fill {
  height: 100%;
  transition: all 0.4s ease;
  border-radius: 3px;
  position: relative;
}

.strength-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.strength-fill.weak { background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%); }
.strength-fill.fair { background: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%); }
.strength-fill.good { background: linear-gradient(135deg, #48bb78 0%, #38a169 100%); }
.strength-fill.strong { background: linear-gradient(135deg, #38a169 0%, #2f855a 100%); }
.strength-fill.very-strong { background: linear-gradient(135deg, #2f855a 0%, #276749 100%); }

.strength-text {
  font-weight: 700;
  min-width: 50px;
  text-align: right;
}

.strength-text.weak { color: #f56565; }
.strength-text.fair { color: #ed8936; }
.strength-text.good { color: #48bb78; }
.strength-text.strong { color: #38a169; }
.strength-text.very-strong { color: #2f855a; }

.error-alert {
  margin-bottom: 20px;
  border-radius: 12px;
  border: none;
  background: rgba(254, 226, 226, 0.9);
  backdrop-filter: blur(10px);
}

.login-actions {
  margin-bottom: 32px;
}

.login-button {
  width: 100%;
  height: 52px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  font-size: 17px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
  position: relative;
  overflow: hidden;
}

.login-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4);
}

.login-button:hover::before {
  left: 100%;
}

.login-button:active {
  transform: translateY(0);
}

.security-tips {
  border-top: 2px solid rgba(226, 232, 240, 0.8);
  padding-top: 24px;
}

.tips-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 15px;
  font-weight: 600;
  color: #4a5568;
}

.tips-title .el-icon {
  color: #667eea;
  font-size: 18px;
}

.tips-content {
  space-y: 12px;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
  font-size: 14px;
  color: #4a5568;
  line-height: 1.5;
}

.tip-item:last-child {
  margin-bottom: 0;
}

.tip-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 8px;
  flex-shrink: 0;
  margin-top: 1px;
}

.tip-icon .el-icon {
  color: #667eea;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    margin: 20px;
    padding: 36px 28px;
    border-radius: 20px;
  }
  
  .app-title {
    font-size: 28px;
  }
  
  .app-subtitle {
    font-size: 15px;
  }
  
  .icon-wrapper {
    width: 70px;
    height: 70px;
    border-radius: 16px;
  }
  
  .icon-wrapper .el-icon {
    font-size: 48px;
  }
  
  .login-form :deep(.el-input) {
    height: 48px;
  }
  
  .login-button {
    height: 48px;
    font-size: 16px;
  }
}
</style>
